import Model from '../abstract';
import ModelCatalogOption from './option';
import ModelCatalogImage from './image';

export default class ModelCatalogProduct extends Model {

      constructor() {
            super();
            this.mainTable = 'product';
            this.pk = 'product_id';
            this.serverPk = 'server_product_id';
            this.versionName = 'version';
            this.dateAddedName = 'date_added';
            this.lastUpdatedName = 'last_updated';
            this.modelOption = new ModelCatalogOption();
            this.modelImage = new ModelCatalogImage();
      }

      /**
       * 获取商品列表
       */
      async getProducts(start = 0, limit = 0) {
            let products = await this.query(start, limit);
            for (product of products) {
                  let productId = product.product_id;
                  product.gallery = await this.modelImage.getGallery(productId);
                  product.options = await this.modelOption.getOptions(productId);
                  product.categories = await this.getCategoryIds(productId);
            }
            return products;
      }

      /**
       * 根据商品分类ID获取商品列表
       */
      async getProductsByCategory(categoryId, start = 0, limit = 0) {
            let products = await this.fetchRows(sprintf("SELECT p.* FROM `%s` AS p INNER JOIN `%s` AS p2c ON p.product_id = p2c.product_id WHERE p2c.category_id = ? ORDER BY %s",  
                  this.mainTable, "product_to_category", "p.sort_order ASC"), 
                  [categoryId], start, limit
            );
            for (product of products) {
                  let productId = product.product_id;
                  product.gallery = await this.modelImage.getGallery(productId);
                  product.options = await this.modelOption.getOptions(productId);
                  product.categories = await this.getCategoryIds(productId);
            }
            return products;
      }

      /**
       * 获取商品资料
       */
      async getProduct(productId) {
            let product = await this.get(productId);
            if (product && product.product_id) {
                  product.gallery = await this.modelImage.getGallery(productId);
                  product.options = await this.modelOption.getOptions(productId);
                  product.categories = await this.getCategoryIds(productId);
            }
            return product;
      }

      /**
       * 保存商品
       */
      async saveProduct(data, productId = 0) {
            let options = [];
            let categories = [];
            let images = [];

            if (data.images) {
                  images = data.images;
                  delete data.images;
            }

            if (data.options) {
                  options = data.options;
                  delete data.options;
            }

            if (data.categories) {
                  categories = data.categories;
                  delete data.categories;
            }

            productId = parseInt(productId);
            productId = await this.save(data, productId);
            if (productId > 0) {
                  await this.modelImage.saveImages(productId, images);
                  await this.modelOption.saveOptions(productId, options);
                  await this.saveCategoryIds(productId, categories);
            }
            return productId;
      }

      /**
       * 通过serverPk保存数据
       */
      async saveProductByServerPk(data, serverProductId = 0) {
            let options = [];
            let categories = [];
            let images = [];

            if (data.images) {
                  images = data.images;
                  delete data.images;
            }
            
            if (data.options) {
                  options = data.options;
                  delete data.options;
            }
            if (data.categories) {
                  categories = data.categories;
                  delete data.categories;
            }

            let productId = await this.saveByServerPk(data, serverProductId);
            if (productId > 0) {
                  await this.modelImage.saveImagesByServerPk(productId, images);
                  await this.modelOption.saveOptionsByServerPk(productId, options);
                  await this.saveCategoryIdsByServerPks(productId, categories);
            }
            return productId;
      }

      /**
       * 保存商品分类
       */
      async saveCategoryIds(productId, ids = []) {
            if (productId > 0) {
                  if (!Array.isArray(ids)) {
                        ids = [];
                  }
                  let oldIds = await this.getCategoryIds(productId);
                  let newIds = ids.filter(el => !oldIds.includes(el));
                  let delIds = oldIds.filter(el => !ids.includes(el));
                  for (id of newIds) {
                        if (id > 0) {
                              let data = {
                                    product_id: productId,
                                    category_id: id
                              };
                              await this.insert("product_to_category", data);
                        }
                  }
                  for (id of delIds) {
                        let params = {
                              product_id: productId,
                              category_id: id
                        };
                        await this.delete("product_to_category", params);
                  }
            }
      }

      /**
       * 保存商品分类
       */
      async saveCategoryIdsByServerPks(productId, serverIds = []) {
            let ids = [];
            if (!Array.isArray(serverIds)) {
                  serverIds = [];
            }
            for (serverId of serverIds) {
                  let id = await this.getCategoryIdByServerPk(serverId);
                  ids.push(id);
            }
            //console.log(ids);
            await this.saveCategoryIds(productId, ids);
      }

      /**
       * 获取当前商品分类ID
       */
      async getCategoryIds(productId) {
            let ids = [];
            let categories = await this.fetchRows("SELECT `category_id` FROM `product_to_category` WHERE `product_id` = ?", [productId]);
            for (category of categories) {
                  ids.push(category.category_id);
            }
            return ids;
      }

      /**
       * 获取当前商品分类ID
       */
      async getCategoryIdByServerPk(serverPk) {
            let row = await this.fetchOne("SELECT `category_id` FROM `category` WHERE `server_category_id` = ? LIMIT 0,1", [serverPk]);
            if (row && row.category_id) {
                  return row.category_id;
            }
            return 0;
      }

      /**
       * 删除商品资料
       */
      async removeProduct(productId) {
            // 删除商品选项数据
            await this.modelOption.removeOptions(productId);
            // 删除商品图片数据
            await this.modelImage.removeImages(productId);
            // 删除本条商品分类数据
            await this.delete("product_to_category", {product_id: productId});
            // 删除本条商品数据
            await this.remove(productId);
      }

      /**
       * 删除商品分类
       */
      async removeProductByServerPk(serverPk) {
            let productId = await this.getIdByServerPk(serverPk);
            if (productId > 0) {
                  return await this.removeProduct(productId);
            }
            return false;
      }

      /**
       * 清除商品数据
       */
      async clean() {
            let products = await this.getProducts();
            for(product of products) {
                  let productId = product.product_id;
                  await this.removeProduct(productId);
            }
            return true;
      }

      
      /**
       * 数据导入
       */
      async download(rows = []) {
            if (!Array.isArray(rows)) {
                  rows = [];
            }

            let localServerPks = await this.getServerPks();
            let remoteServerPks = [];
            for (row of rows) {
                  let serverPk = row.server_product_id;
                  remoteServerPks.push(serverPk);
                  let pk = await this.saveProductByServerPk(row, serverPk);
                  //console.log("product >>>> ", pk);
            }

            let delServerPks = localServerPks.filter(el => !remoteServerPks.includes(el));
            for (serverPk of delServerPks) {
                  if (serverPk > 0) {
                        await this.removeProductByServerPk(serverPk);
                  }
            }
            
            return true;
      }

      /**
       * 数据上传
       */
      async upload() {
            return true;
      }
}